<template>
  <div class="syllabuscontainer schedule-course">
    <!-- 教务管理头部 -->
    <el-row class="title_StudentManage">
      <el-row class="toprow">
        <i class="el-icon-arrow-left btn" @click="changeClassTime(-1)"></i>
        <span class="timetxt">{{newcalendar.weekTime}}</span>
        <i class="el-icon-arrow-right btn" @click="changeClassTime(1)"></i>
      </el-row>
    </el-row>

    <!-- 课程表显示 -->
    <div class="calendarBox">
      <!-- 一个小时 高度 一行一小时 -->
      <div class="week" :style="'display:'+week.display" ref="weekBox">
        <!-- 背景表格 -->
        <template>
          <el-table
            :data="yaxisData"
            border
            class="newbacktable"
            @cell-mouse-enter="WeekHover"
            @cell-mouse-leave="WeekLeave"
            @cell-click="WeekClick"
            @cell-dblclick="WeekDblclick"
          >
            <el-table-column prop="time" :width="dayWeekFirstColumWidth">
              <template slot="header" slot-scope="scope"></template>
            </el-table-column>

            <el-table-column prop="Monday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[0].select"></i>
                <span :class="'dayofweek '+week.head[0].select">{{week.head[0].dayofweek}}</span>
                <span :class="'date '+week.head[0].select">{{week.head[0].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Tuesday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[1].select"></i>
                <span :class="'dayofweek '+week.head[1].select">{{week.head[1].dayofweek}}</span>
                <span :class="'date '+week.head[1].select">{{week.head[1].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Wednesday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[2].select"></i>
                <span :class="'dayofweek '+week.head[2].select">{{week.head[2].dayofweek}}</span>
                <span :class="'date '+week.head[2].select">{{week.head[2].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Thursday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[3].select"></i>
                <span :class="'dayofweek '+week.head[3].select">{{week.head[3].dayofweek}}</span>
                <span :class="'date '+week.head[3].select">{{week.head[3].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Friday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[4].select"></i>
                <span :class="'dayofweek '+week.head[4].select">{{week.head[4].dayofweek}}</span>
                <span :class="'date '+week.head[4].select">{{week.head[4].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Saturday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[5].select"></i>
                <span :class="'dayofweek '+week.head[5].select">{{week.head[5].dayofweek}}</span>
                <span :class="'date '+week.head[5].select">{{week.head[5].date}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="Sunday" :width="week.tablecolumWidth">
              <template slot="header" slot-scope="scope">
                <i :class="'el-icon-caret-bottom arrow '+week.head[6].select"></i>
                <span :class="'dayofweek '+week.head[6].select">{{week.head[6].dayofweek}}</span>
                <span :class="'date '+week.head[6].select">{{week.head[6].date}}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 课程叠加 -->
        <div
          class="newclassLayerBox"
          ref="classLayerBox_week"
          v-html="week.classHtml"
          @click="showGradeDetails(2,$event,-1)"
        ></div>
        <!-- 当前时间横线 -->
        <div class="timeline" ref="timeline_week">
          <i class="el-icon-caret-right"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from "vuex"; //先要引入

let vm;
export default {
  props: ["syllabusData"],
  data() {
    return {
      parentData: this.syllabusData,
      newcalendar: {
        selectCell: null,
        isMove: true,
        classhour: 2,
        isShow: false,
        modalclose: false,
        newclass: "",
        classlist: [{ label: "一班", value: "1" }],
        startDate: "",
        selectDate: null,
        weekTime: ""
      },

      /**课程表显示 */

      dayWeekFirstColumWidth: 70, //天宽度
      week: {
        display: "block",
        /**顶部时间切换标签记录 */
        timechange: 0,
        tablecolumWidth: 207,
        head: [
          {
            dayofweek: "星期一",
            date: "03.24",
            select: ""
          },
          {
            dayofweek: "星期二",
            date: "03.25",
            select: ""
          },
          {
            dayofweek: "星期三",
            date: "03.26",
            select: ""
          },
          {
            dayofweek: "星期四",
            date: "03.27",
            select: "select"
          },
          {
            dayofweek: "星期五",
            date: "03.28",
            select: ""
          },
          {
            dayofweek: "星期六",
            date: "03.29",
            select: ""
          },
          {
            dayofweek: "星期日",
            date: "03.30",
            select: ""
          }
        ],

        seriesData_primary: [], //原始排课数据
        seriesData_analyse: [], //分析排课冲突后数据
        classHtml: ""
      },
      //时间轴数据 1小时间隔
      yaxisMaxtime: config.campusTime.maxEndTime, //注：最大时间为yaxisData最大时间加一个小时
      yaxisMintime: config.campusTime.minStartTime,
      //	oneHourHeight:0.90,//y轴一小时的高度 rem
      oneHourHeight: 1, //y轴一小时的高度 rem
      yaxisData: config.timtlist,
      /**当前课程表开始时间 */
      g_startTime: null,
      /**当前课程表结束时间 */
      g_endTime: null
    };
  },
  methods: {
    /**veu 数组深度复制 解耦 */
    deepCloneArray(arr) {
      return arr.map(e => {
        if (typeof e === "object") {
          return Object.assign({}, e);
        } else {
          return e;
        }
      });
    },
    /**字符串转Date
     * 形如"2019-03-26 15:50"
     */
    stringToDate(s) {
      // var s ='2018-10-09 10:23:12';
      s = s + ":00";
      s = s.replace(/-/g, "/");
      return new Date(s);
    },
    /**
     * 对象转时间字符串
     */
    objToTimeStr(start, end) {
      let startmonth = start.month < 10 ? "0" + start.month : start.month;
      let endmonth = end.month < 10 ? "0" + end.month : end.month;
      let startday = start.day < 10 ? "0" + start.day : start.day;
      let endday = end.day < 10 ? "0" + end.day : end.day;
      return {
        start: start.year + "-" + startmonth + "-" + startday + " 00:00:00",
        end: end.year + "-" + endmonth + "-" + endday + " 23:59:59"
      };
    },
    //初始化
    init() {
      let rem = screen.width / 19.2;
      this.dayWeekFirstColumWidth = 0.7 * rem;
      this.week.tablecolumWidth = 2.06 * rem;
      this.week.timechange = 0;
      this.campusId = this.$store.state.campusId;

      this.yaxisMaxtime = config.campusTime.maxEndTime; //注：最大时间为yaxisData最大时间加一个小时
      this.yaxisMintime = config.campusTime.minStartTime;
      this.yaxisData = config.timtlist;
      console.log(this.yaxisData);

      //更新一天的开始结束时间
      //		this.setDayTime(this.parentData.dayStartTime,this.parentData.dayEndTime);
      //容器高度
      let height =
        this.yaxisData.length * this.oneHourHeight + this.oneHourHeight + 0.2;

      this.$refs.weekBox.style.height = height + "rem";
      //更新头部
      this.updateHeadTimeChangeControl();

      //初始化课程表叠加图层div的高度，要和底层的table保持一致
      this.updateLayerBoxHeight(this, this.$refs.classLayerBox_week);
      //时间线更新 每分钟更新时间线的位置

      // this.updateTimeLineInTime();
      //根据条件更新排课数据
      this.updateClassTableByCondition();

      this.$emit("parentMethods", { event: "resettime" });
    },

    /**
     * 日历一天的开始时间与结束时间设置
     */
    setDayTime(dayStartTime, dayEndTime) {
      let startHour = dayStartTime.split(":")[0];
      let endHour = dayEndTime.split(":")[0];
      startHour =
        Number(startHour.at(0)) == 0
          ? Number(startHour.at(1))
          : Number(startHour);
      endHour =
        Number(endHour.at(0)) == 0 ? Number(endHour.at(1)) : Number(endHour);
      this.yaxisMaxtime = endHour + 1;
      this.yaxisMintime = startHour;
      //yaxisData
      this.yaxisData = [];
      //   debugger
      for (let i = startHour; i <= endHour; i++) {
        let hour = i < 10 ? "0" + i + ":00" : i + ":00";
        this.yaxisData.push({ time: hour });
      }
    },
    /**
     * 关闭日历组件
     */
    clearCourselist() {
      this.week.classHtml = "";
    },
    /**获取数据 */
    api_getDataByParam(param, successFun) {
      let self = this;
      self.parentData.dataloading = true;

      let timeline_week = this.$refs.timeline_week;

      let dayBox = this.$refs.dayBox,
        weekBox = this.$refs.weekBox;

      param.campusId = this.campusId;

      api
        .querySyllabusForSyllabus(param)
        .then(function(d) {
          if (d.result === "操作成功") {
            // console.log(d)
            let data = d.listSyllabus;
            let maxHour = 0,
              minHour = 24;
            //数据格式化
            let result = [];
            for (let i = 0; i < data.length; i++) {
              let row = data[i];
              //时间
              row.starttime = self.stringToDate(row.startTime);
              row.endtime = self.stringToDate(row.endTime);

              let h1 = parseInt(
                row.starttime.getHours() + row.starttime.getMinutes() / 60
              );
              let h2 = Math.ceil(
                row.endtime.getHours() + row.endtime.getMinutes() / 60
              );
              let minShowTime = parseInt(vm.yaxisData[0].time.split(":")[0]); //获取 当天最小显示的上课时间
              let maxShowTime = parseInt(
                vm.yaxisData[vm.yaxisData.length - 1].time.split(":")[0]
              ); //获取 当天最大显示的上课时间

              if (h1 < minShowTime || h2 > maxShowTime) continue;
              minHour = minHour > h1 ? h1 : minHour;
              maxHour = maxHour < h2 ? h2 : maxHour;
              //字段改名
              row.classname = row.className || "-";
              row.assistant = row.assisUserName || "-";
              row.teacherName = row.teacherUserName || "-";
              result.push(row);
            }

            successFun(result);
          }
          self.parentData.dataloading = false;
        })
        .catch(function() {
          self.parentData.dataloading = false;
        });
    },
    /**更新课程表数据 父组件调用此方法更新数据
     * 条件：
     *  包括组件本身的时间维度、时间范围；
     *  以及父组件传递过来的班级、教师、教室、课程
     */
    updateClassTableByCondition() {
      this.updateTimeLinePosition(this, this.$refs.timeline_week);

      let grade = this.parentData.classtext; //班级id
      let teacher = this.parentData.teachertext; //教师id
      let classroom = this.parentData.classroomtext; //教室id
      let course = this.parentData.coursetext; //课程id
      let isTrialClass = this.parentData.isTrialClass; //是否包含试听课
      let classOrTrialClass = this.parentData.classOrTrialClass; //是否是试听班级
      let start = this.g_startTime; //当前周开始日期
      let end = this.g_endTime; //当前周结束日期
      let teacherOrAssitUserId = this.parentData.assistertext
        ? this.parentData.assistertext
        : "";

      let timeobj = this.objToTimeStr(start, end);
      let postData = {
        classId: grade,
        classOrTrialClass: classOrTrialClass,
        teacherUserId: teacher,
        classroomId: classroom,
        startTime: timeobj.start,
        endTime: timeobj.end,
        containTrialClass: isTrialClass
      };

      let self = this;
      //接口
      let list = [];
      //待排课列表
      let courselist = vm.$store.state.courselist;
      list = courselist.map(function(row) {
        let stime = new Date(row.curDate + " " + row.starttime + ":00");
        let etime = new Date(row.curDate + " " + row.endTime + ":00");

        return {
          starttime: stime,
          startTime: row.curDate + " " + row.starttime,
          endtime: etime,
          endTime: row.curDate + " " + row.endTime,
          classname: vm.parentData.classInfo.className,
          classId: vm.parentData.classInfo.classId,
          conflict: false,
          classCourseCount: vm.parentData.classInfo.courseDateCount,
          orderBy: vm.parentData.classInfo.useCourseHour,
          teacherName: row.teacherUserName || "",
          classroomName: row.classRoomName || "",
          courseName: row.courseName,
          coursetype: "排课",
          uuid: row.uuid
        };
      });

      if (postData.teacherUserId == "" && postData.classroomId == "") return;
      //获取排课列表
      this.api_getDataByParam(postData, d => {
        self.week.seriesData_primary = d;
        //处理冲突排课
        self.week.seriesData_analyse = self.groupClassItemByTime(
          self.week.seriesData_primary
        );

        if (list.length > 0) {
          //如果待排课列表有值才插入

          for (let i = 0; i < list.length; i++) {
            self.week.seriesData_analyse.push([list[i]]);
          }
        }
        //将排课数据绘制在表中
        self.drawClassTableByGroupData_week(self.week.seriesData_analyse);
      });
    },

    /**更新时间 顶部左右切换按钮 */
    changeClassTime(add) {
      let courselist = vm.$store.state.courselist;
      if (courselist.length > 0) {
        //存在待排课课程列表

        this.$confirm("请先保存本周课程排课,否则自动清空,是否保存？", "", {
          confirmButtonText: "保存排课",
          cancelButtonText: "取消当前排课",
          type: "warning"
        })
          .then(() => {
            //排课方法
            this.$emit("parentMethods", { event: "save" });
            this.$emit("parentMethods", { event: "resettime" });
          })
          .catch(() => {
            vm.$store.commit("clearCourselist", []); //清空已存排课列表
            this.week.timechange += add;
            this.updateHeadTimeChangeControl(this.week.timechange);
            this.updateClassTableByCondition();
          });
      } else {
        vm.$store.commit("clearCourselist", []); //清空已存排课列表
        this.week.timechange += add;
        this.updateHeadTimeChangeControl(this.week.timechange);
        this.updateClassTableByCondition();
        this.$emit("parentMethods", { event: "resettime" });
      }
    },
    /**更新顶部时间切换标签
     * type 类型 今日 本周 本月
     * add 变化时间 type为今日时，加减天；为周，加减一周
     */
    updateHeadTimeChangeControl(add = 0) {
      let daytime = new Date(this.parentData.currentTime);
      daytime.setDate(daytime.getDate() + add * 7);
      let num = daytime.getDay() || 7;
      daytime.setDate(daytime.getDate() - num + 1); //本周第一天
      let month = daytime.getMonth() + 1;
      month = month < 10 ? "0" + month : month;
      let day = daytime.getDate();
      day = day < 10 ? "0" + day : day;
      let start = daytime.getFullYear() + "." + month + "." + day;

      this.g_startTime = {
        year: daytime.getFullYear(),
        month: daytime.getMonth() + 1,
        day: daytime.getDate()
      };

      //同时更新表格头部
      this.updateHead({
        today: false,
        weekstart: {
          year: daytime.getFullYear(),
          month: daytime.getMonth(),
          day: daytime.getDate()
        }
      });

      daytime.setDate(daytime.getDate() + 6); //本周最后一天
      month = daytime.getMonth() + 1;
      month = month < 10 ? "0" + month : month;
      day = daytime.getDate();
      day = day < 10 ? "0" + day : day;
      let end = daytime.getFullYear() + "." + month + "." + day;
      this.g_endTime = {
        year: daytime.getFullYear(),
        month: daytime.getMonth() + 1,
        day: daytime.getDate()
      };

      this.newcalendar.weekTime = start + " - " + end;
    },
    /**
     * 更新课程表叠加图层div的高度，要和底层的table保持一致
     */
    updateLayerBoxHeight(self, classLayerBox_week) {
      let height = self.yaxisData.length * self.oneHourHeight;

      classLayerBox_week.style.height = height + "rem";
      classLayerBox_week.style.top = "-" + height + "rem";
    },
    /**时间线更新 每分钟更新时间线的位置 */
    updateTimeLineInTime() {
      // let self=this;
      // let timeline_day=this.$refs.timeline_day;
      // let timeline_week=this.$refs.timeline_week;
      // setInterval(function(){
      // 	self.updateTimeLinePosition(self,timeline_day,timeline_week);
      // },60*1000);
    },
    updateTimeLinePosition(self, timeline_week) {
      // console.log('时间线更新')
      //	debugger
      let time = new Date();
      let hour = time.getHours();
      let minute = time.getMinutes();
      if (hour < self.yaxisMintime) {
        hour = self.yaxisMintime;
        minute = 0;
      } else if (hour >= self.yaxisMaxtime) {
        hour = self.yaxisMaxtime;
        minute = 0;
      }
      let persent =
        (hour + minute / 60 - self.yaxisMintime) /
        (self.yaxisMaxtime - self.yaxisMintime);
      let height = self.yaxisData.length * self.oneHourHeight;
      let startY = -2 * height;
      let endY = startY + persent * height;
      // console.log(endY)
      // console.log(self.$refs)
      //	timeline_day.style.top=endY+'rem';
      timeline_week.style.top = endY + "rem";
    },
    /**更新表格头部 星期 */
    updateHead(timeObj) {
      let now = new Date();

      //本周头部更新
      if (timeObj.weekstart) {
        let tempday = new Date(
          timeObj.weekstart.year,
          timeObj.weekstart.month,
          timeObj.weekstart.day,
          0,
          0,
          0
        );
        //this.$refs.timeline_day.style.visibility='hidden';
        this.$refs.timeline_week.style.visibility = "hidden";
        for (let i = 0; i < 7; i++) {
          let tmonth = tempday.getMonth() + 1;
          tmonth = tmonth < 10 ? "0" + tmonth : tmonth;
          let tday = tempday.getDate();
          tday = tday < 10 ? "0" + tday : tday;

          let select = "";
          if (
            tempday.getFullYear() === now.getFullYear() &&
            tempday.getMonth() === now.getMonth() &&
            tempday.getDate() === now.getDate()
          ) {
            select = "select";
            //	this.$refs.timeline_day.style.visibility='visible';
            this.$refs.timeline_week.style.visibility = "visible";
          }

          let tdate = tmonth + "." + tday;
          this.week.head[i].date = tdate;
          this.week.head[i].select = select;
          this.week.head[i].paradate =
            tempday.getFullYear() + "-" + tmonth + "-" + tday;
          tempday.setDate(tempday.getDate() + 1);
        }
      }
    },
    /**
     * 判断时间是否重合
     * 重合 返回true
     */
    isTimeContains(
      startObj,
      endObj,
      startField = "starttime",
      endField = "endtime"
    ) {
      let st1 = startObj[startField],
        et1 = startObj[endField],
        st2 = endObj[startField],
        et2 = endObj[endField];
      let result = false;
      let combineStart, combineEnd;
      combineStart = st1;
      combineEnd = et1 > et2 ? et1 : et2;
      if (st1 > st2) {
        combineStart = st2;
        if (et2 > st1) {
          result = true;
        }
      } else if (st1 === st2) {
        result = true;
      } else {
        if (st2 < et1) {
          result = true;
        }
      }
      return { contains: result, start: combineStart, end: combineEnd };
    },
    /**
     * 判断两个课表是否冲突
     * 冲突 返回true
     */
    isClassConlict(
      d1,
      d2,
      nameField = "teacherName",
      assistantField = "assistant",
      classrommField = "classroomName"
    ) {
      if (!this.isTimeContains(d1, d2).contains) {
        return false;
      }
      if (d1.conflict) {
        for (let i = 0; i < d1[nameField].length; i++) {
          if (
            d1[nameField][i] === d2[nameField] ||
            // d1[assistantField][i]===d2[assistantField]||
            d1[classrommField][i] === d2[classrommField]
          )
            return true;
          else return false;
        }
      } else {
        if (
          d1[nameField] === d2[nameField] ||
          // d1[assistantField]===d2[assistantField]||
          d1[classrommField] === d2[classrommField]
        )
          return true;
        else return false;
      }
    },

    combineConlictClass(row1, row2) {
      let rowj = row1;
      let rowk = row2;
      let start =
        rowk.starttime > rowj.starttime ? rowj.starttime : rowk.starttime;
      let end = rowk.endtime > rowj.endtime ? rowk.endtime : rowj.endtime;
      let result = {
        starttime: start,
        endtime: end,
        conflict: true
      };
      if (rowj.conflict) {
        for (let key2 in rowj) {
          if (key2 === "starttime" || key2 === "endtime" || key2 === "conflict")
            continue;
          result[key2] = rowj[key2].concat([rowk[key2]]);
        }
      } else {
        for (let key2 in rowj) {
          if (key2 === "starttime" || key2 === "endtime" || key2 === "conflict")
            continue;
          result[key2] = [rowj[key2], rowk[key2]];
        }
      }
      return result;
    },
    /**根据时间获取课表位置相关信息 */
    getClassPositionByTime(start, end) {
      let startNum = start.getHours() + start.getMinutes() / 60;
      let endNum = end.getHours() + end.getMinutes() / 60;
      let height = (endNum - startNum) * this.oneHourHeight;

      let top = (startNum - this.yaxisMintime) * this.oneHourHeight;
      return { top: top, height: height };
    },
    /**按时间将课程表数据分行
     * 分类：按起止时间分析，当时间存在重合时，归为一行
     * 课程存在冲突:时间重合 and (教师名称相同 or 助教名称相同 or 教室相同)
     * 当日 本周 本月
     * 返回分类数据
     */
    groupClassItemByTime(dataprimry) {
      let data = this.deepCloneArray(dataprimry);
      //按时间排序
      data.sort((a, b) => {
        if (a.starttime > b.starttime) return 1;
        else if (a.starttime === b.starttime) {
          return 0;
        } else return -1;
      });

      //分组
      let result = [];
      for (let i = 0; i < data.length; i++) {
        let rowi = data[i];
        let temprow = [rowi];
        let combineStart = tool.clone(rowi["starttime"]),
          combineEnd = tool.clone(rowi["endtime"]);
        for (let j = i + 1; j < data.length; j++) {
          let rowj = data[j];
          let obj = this.isTimeContains(
            { starttime: combineStart, endtime: combineEnd },
            rowj
          );
          if (obj.contains) {
            combineStart = obj.start;
            combineEnd = obj.end;
            temprow.push(rowj);
            data.splice(j, 1);
            j--;
          }
        }
        result.push(temprow);
      }
      //检测课程表冲突并合并
      for (let i = 0; i < result.length; i++) {
        let rowi = result[i];
        if (rowi.length == 1) {
          continue;
        }
        for (let j = 0; j < rowi.length; j++) {
          // let rowj=rowi[j];
          for (let k = j + 1; k < rowi.length; k++) {
            // let rowk=rowi[k];
            //若冲突，则去掉k位置的项，合并至j
            if (this.isClassConlict(rowi[j], rowi[k])) {
              rowi[j] = this.combineConlictClass(rowi[j], rowi[k]);
              rowi.splice(k, 1);
              k--;
            }
          }
        }
      }
      // console.log(result)
      return result;
    },
    /**根据分组后的数据绘制课程表本周 */
    drawClassTableByGroupData_week(data) {
      let classid = this.parentData.classtext; //班级id

      let html = "";
      let now = new Date(),
        splittime = 12;
      for (let i = 0; i < data.length; i++) {
        let rowi = data[i];
        let rowHtml = "";
        let mtop = 90000000;
        let left = 0;
        //获取最小高度
        for (let j = 0; j < rowi.length; j++) {
          let rowj = rowi[j];
          let starttime = rowj.starttime;
          let endtime = rowj.endtime;
          /**课表高度 */
          let position = this.getClassPositionByTime(starttime, endtime);
          if (mtop > position.top) mtop = position.top;
        }
        for (let j = 0; j < rowi.length; j++) {
          let rowj = rowi[j];
          let starttime = rowj.starttime;
          let endtime = rowj.endtime;
          let week = starttime.getDay() || 7;
          if (week < 1) continue;
          left = (week - 1) * 2.06;
          /**课表高度 */
          let position = this.getClassPositionByTime(starttime, endtime);
          let classItemTop = 0;
          if (mtop < position.top) {
            classItemTop = position.top - mtop;
          }
          // if(preHeight<position.height)preHeight=position.height;
          /**课程状态：冲突 完成 上午 下午 */
          let type = "blue";
          let curClass = "";
          if (endtime.getHours() > splittime) {
            type = "yellow";
          }
          if (rowj.attendMode === 1) {
            type = "gray";
          }
          /**课程内容描述 */
          let innerhtml = "";
          let clickItem = "clickItem";
          let indexKey = `${i},${j},-1`;
          let classSyllabusId = rowj.classSyllabusId || "";
          let uuid = rowj.uuid || "";
          let title = ``;
          //	debugger
          if (rowj.conflict) {
            //冲突课次
            type = "red";
            clickItem = "";
            indexKey = "";
            for (let m = 0; m < rowj.classname.length; m++) {
              let cid = rowj.classId[m];
              let thiscls = "";
              if (cid == classid) {
                //判断是否是当前选中班
                thiscls = "classstyle";
              } else {
                thiscls = "opacity";
              }
              //判断是否是全日班
              // debugger
              if (rowj.courseType[m] == 2) {
                //全日制
                let starttime = rowj.startTime[m].split(" ");
                let endtime = rowj.endTime[m].split(" ");
                let time = starttime[0] + " " + starttime[1] + "-" + endtime[1];
                innerhtml += `
											<div class="errorRow errorRow${m +
                        1} clickItem  ${thiscls}" indexKey="${i},${j},${m}" uuid="${uuid}" classSyllabusId="${classSyllabusId}"
										
											title="上课时间：${time}&#10;班级：${rowj.classname[m]}&#10;课程：${
                  rowj.courseName[m]
                }&#10;教师：${rowj.teacherName[m]}&#10;教室：${rowj
                  .classroomName[m] || ""}">
											<span class="classname">${rowj.classname[m]}</span>
											<span class="courseName">${rowj.courseName[m]}</span><br>
											<span class="teacherName">${rowj.teacherName[m]}</span>	
											<span class="classRoom">${rowj.classroomName[m] || ""}</span>	
											</div>
										`;
              } else {
                let starttime = rowj.startTime[m].split(" ");
                let endtime = rowj.endTime[m].split(" ");
                let time = starttime[0] + " " + starttime[1] + "-" + endtime[1];
                innerhtml += `
											<div class="errorRow errorRow${m +
                        1} clickItem ${thiscls}" indexKey="${i},${j},${m}" uuid="${uuid}" classSyllabusId="${classSyllabusId}"
											
											title="上课时间：${time}&#10;班级：${rowj.classname[m]}&#10;课程：${
                  rowj.courseName[m]
                }&#10;教师：${rowj.teacherName[m]}&#10;教室：${rowj
                  .classroomName[m] || ""}">
											<span class="classname">${rowj.classname[m]}</span>
											<span class="courseName">${rowj.courseName[m] || ""}<br>
											<span class="teacherName">${rowj.teacherName[m]}</span>	
											<span class="classRoom">${rowj.classroomName[m] || ""}</span>	
											</div>
											`;
              }
            }
          } else {
            //未冲突

            if (rowj.classId == classid) {
              type = "thiscls"; //判断是否是当前选中班
              curClass = "";
            } else {
              curClass = "opacity";
            }
            let starttime = rowj.startTime.split(" ");
            let endtime = rowj.endTime.split(" ");
            let time = starttime[0] + " " + starttime[1] + "-" + endtime[1];
            title = `title="上课时间：${time}&#10;班级：${
              rowj.classname
            }&#10;课程：${rowj.courseName}&#10;教师：${
              rowj.teacherName
            }&#10;教室：${rowj.classroomName || ""}"`;
            //判断是否是全日班

            if (rowj.courseType == 2) {
              //全日制
              innerhtml = `
										<span class="classname">${rowj.classname}</span>
										<span class="courseName">${rowj.courseName}</span>
										<span class="teacherName">${rowj.teacherName}</span>	
										<span class="classRoom">${rowj.classroomName || ""}</span>	
										`;
            } else if (rowj.coursetype == "排课") {
              type = "temp";
              innerhtml = `
										<span class="classname">${rowj.classname}</span>
										<span class="courseName">${rowj.courseName}</span>
										<span class="teacherName">${rowj.teacherName}</span>
										<span class="classRoom">${rowj.classroomName || ""}</span>	
										`;
            } else {
              innerhtml = `
										<span class="classname">${rowj.classname}</span>
										<span class="courseName">${rowj.courseName || ""}</span>	
										<span class="teacherName">${rowj.teacherName}</span>
										<span class="classRoom">${rowj.classroomName || ""}</span>	
										`;
            }
          }
          rowHtml += `<div class="classItem ${type} ${clickItem} ${curClass}"  indexKey="${indexKey}"  uuid="${uuid}" classSyllabusId="${classSyllabusId}"
					${title}
					style="height:${position.height}rem;margin-top:${classItemTop}rem;">${innerhtml}</div>`;
        }
        rowHtml =
          `<div class="rowItem"  style="top:${mtop}rem;left:${left}rem;">` +
          rowHtml +
          "</div>";
        html += rowHtml;
      }
      this.week.classHtml = html;
      // console.log(html)
    },
    /**
     * 获取本月的初始化日期数据
     * 注：月份为实际月份减1,如：1月，应为0
     *  */
    getMonthDateByTime(
      year = new Date().getFullYear(),
      month = new Date().getMonth()
    ) {
      let now = new Date();
      let firstDay = new Date(year, month, 1); //本月第一天
      let lastDay = new Date(year, month + 1, 0); //本月最后一天
      let weekstart = firstDay.getDay();
      let addday = 0;
      if (weekstart === 0) {
        addday = 1;
      } else {
        addday = -weekstart + 1;
      }
      let countday = 6 * 7;
      let result = [];
      let k = 0;
      for (let i = addday; k < countday; i++) {
        let tempday = new Date(year, month, i);
        result.push({
          date: tempday.getDate(),
          class: [],
          year: tempday.getFullYear(),
          month: tempday.getMonth(),
          isMonth: now.getMonth() === tempday.getMonth() ? "thisMonth" : "",
          isToday: now.getDate() === tempday.getDate() ? true : false
        });
        k++;
      }
      return result;
    },

    /**
     * 班级详情弹窗
     * type 1:day ;2 week；3：month
     * data type=1:dom;type=2:班级数据
     * index type=1:undefine;type=2:大于0则为冲突
     */
    showGradeDetails(type, data, index) {
      let anlysedata = this.week.seriesData_analyse;
      if (data.target.className.includes("clickItem")) {
        let classSyllabusId = data.target.getAttribute("classSyllabusId");
        let indexKey = data.target.getAttribute("indexKey");
        if (classSyllabusId != "") {
          //已排好课程
          let index = Number(indexKey.split(",")[2]);
          let id = "";
          let courseObj;
          if (index < 0) {
            id = classSyllabusId;
          } else {
            id = classSyllabusId.split(",")[index];
          }
          //获取要编辑的排课课次
          for (let i = 0; i < this.week.seriesData_primary.length; i++) {
            let li = this.week.seriesData_primary[i];
            if (li.classSyllabusId == id) {
              courseObj = li;
            }
          }

          console.log(courseObj);
          //判断是否已上课
          if (courseObj.attendMode != 2 && courseObj.attendMode != 0) {
            this.$message({
              message: "本课次已上课",
              type: "warning"
            });
            return;
          } else {
            this.$emit("parentMethods", {
              event: "editored",
              courseObj: courseObj
            });
          }
        } else {
          //未排好课课次
          let uuid = data.target.getAttribute("uuid");
          let templist = vm.$store.state.courselist; //

          for (let i = 0; i < templist.length; i++) {
            let li = templist[i];
            if (li.uuid == uuid) {
              //console.log(li)
              this.$emit("parentMethods", { event: "editor", uuid: li.uuid });
            }
          }
        }
      }
    },
    /**
     * 周单元格点击事件
     * row 行对象 column 列对象 cell 单元格对象 event 事件
     */
    WeekClick(row, column, cell, event) {
      if (column.property == "time") return;

      let weeks = {
        Monday: "1",
        Tuesday: "2",
        Wednesday: "3",
        Thursday: "4",
        Friday: "5",
        Saturday: "6",
        Sunday: "0"
      };
      let week = weeks[column.property];
      let time = row.time;
      let index = Number(week);
      if (index == 0) {
        index = 7;
      }
      let curDate = this.week.head[index - 1].paradate;

      this.$emit("parentMethods", {
        event: "click",
        week: week,
        startTime: time,
        curDate: curDate
      });
    },
    /**
     * 周单元格双击事件
     * row 行对象 column 列对象 cell 单元格对象 event 事件
     */
    WeekDblclick(row, column, cell, event) {
      setTimeout(function() {
        vm.newcalendar.isMove = true;
      }, 500);

      if (column.property == "time") return;
      let cellobj = cell.childNodes[0];
      if (cellobj) {
        cellobj.innerHTML = "";
      }
    },
    /**
     * 周单元格鼠标移动事件
     * row 行对象 column 列对象 cell 单元格对象 event 事件
     */
    WeekHover(row, column, cell, event) {
      if (column.property == "time" || !this.newcalendar.isMove) return;
      let weeks = {
        Monday: "周一",
        Tuesday: "周二",
        Wednesday: "周三",
        Thursday: "周四",
        Friday: "周五",
        Saturday: "周六",
        Sunday: "周日"
      };
      let week = weeks[column.property];
      let starttime = row.time;
      let fNumber = Number(starttime.at(0));
      let endtime =
        fNumber == 0
          ? Number(starttime.at(1)) + 1 > 9
            ? Number(starttime.at(1)) + 1 + ":" + "00"
            : "0" + (Number(starttime.at(1)) + 1 + ":" + "00")
          : Number(starttime.split(":")[0]) + 1 + ":" + "00";
      let cellobj = cell.childNodes[0];
      if (cellobj) {
        let elementnode = document.createElement("div");
        elementnode.classList = "WeekMouseClick";
        let html = `<span>${week}</span>&nbsp;&nbsp;<span>${starttime}</span>-<span>${endtime}</span>`;
        elementnode.innerHTML = html;
        cellobj.appendChild(elementnode);
      }
    },
    /**
     * 周鼠标离开单元格事件
     * row 行对象 column 列对象 cell 单元格对象 event 事件
     */
    WeekLeave(row, column, cell, event) {
      if (column.property == "time" || !this.newcalendar.isMove) return;
      let cellobj = cell.childNodes[0];
      if (cellobj) {
        let childlist = cellobj.childNodes;
        for (let i = 0; i < childlist.length; i++) {
          let node = childlist[i].classList;
          let nodearr = Array.from(node);
          if (nodearr.includes("WeekMouseClick")) {
            cellobj.removeChild(childlist[i]);
          }
        }
      }
    }
  },
  mounted() {
    vm = this;
  }
};
</script>

<style lang="scss">
.syllabuscontainer {
  .title_StudentManage {
    background-color: #f5f7fa;
    padding: 0 0.15rem 0 0.15rem;
    border-radius: 0.1rem 0.1rem 0 0;
    line-height: 0.5rem;
    font-size: 0.18rem;
    text-align: center;
    .toprow {
      user-select: none;
      .timetxt {
        margin: 0.2rem;
      }
      .btn:hover {
        cursor: pointer;
        color: #3885f8;
      }
    }
    .timeselect {
    }
  }

  .calendarBox {
    .WeekMouseClick {
      width: 1.98rem;
      /*height: 0.9rem;*/
      height: 1rem;
      border-left: 0.05rem solid;
      border-color: #52c0ff;
      background-color: #e4f5ff;
      color: #52c0ff;
      position: absolute;
      top: 0rem;
      left: 0rem;
      line-height: 1rem;
      margin-left: 0.04rem;
      cursor: pointer;
      z-index: 0;
      display: -webkit-flex; /* Safari */
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      flex-direction: row;
    }

    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background: none;
    }

    //本周
    .week {
      height: 9rem;
      .el-table__header .select {
        color: #3885f8;
      }
      .rowItem {
        width: 2.06rem !important;
      }
      .el-table--scrollable-x .el-table__body-wrapper {
        overflow: hidden !important;
      }
    }
    // 课程表公共
    .newbacktable {
      margin-top: 0rem;
      margin-left: 2%;

      width: 96%;
      tr {
        //一小时的行高
        height: 1rem;
        max-height: 1rem;
        th {
          width: 2.13248rem;
        }
      }
      .dayofweek {
        display: inline-block;
        width: 100%;
        text-align: center;
        // font-weight: 500;
        font-size: 0.17rem;
      }
      .date {
        display: inline-block;
        width: 100%;
        text-align: center;
        // font-weight: 500;
      }
      .arrow {
        // color: #3885f8;
        width: 100%;
        text-align: center;
      }
      .el-table__row td:first-child {
        font-size: 0.16rem;
        color: #666666;
        font-weight: 600;
        width: 0.7rem;
      }
      .el-table__row td:nth-child(1) {
        vertical-align: top;
        padding-top: 0rem;
      }
      .el-table__row td:last-child {
        border-right: 0;
      }
    }

    .el-table--group,
    .el-table--border {
      border: 0;
    }
    .el-table--group::after,
    .el-table--border::after {
      background: rgba(0, 0, 0, 0);
    }
    .el-table__header-wrapper thead th {
      border-right: 0;
    }
    .el-table__header-wrapper thead th:first-child {
      width: 0.7rem;
    }
    .el-table__header-wrapper {
      pointer-events: none;
    }
    .timeline {
      position: relative;
      top: -14.8rem;
      left: 1rem;
      width: 92%;
      height: 0.01rem;
      border: 0.01rem solid #3885f8;
      color: #3885f8;
      pointer-events: none;
      .el-icon-caret-right {
        position: relative;
        left: -0.16rem;
        top: -0.124rem;
      }
    }
    /**
		 * 排课列表数据
		 */
    .newclassLayerBox {
      position: relative;
      top: -7.8rem;
      left: 1.01rem;
      width: 91.5%;
      height: 7.8rem;
      pointer-events: none;
      .rowItem {
        position: relative;
        width: 100%;
        height: 0;
        display: flex;
        justify-content: flex-start;
        pointer-events: auto;
        .classItem {
          border-left: 0.05rem solid;
          width: 100%;
          height: 100%;
          margin-left: 0.04rem;
          margin-right: 0.04rem;
          display: flex;
          flex-direction: column;
          font-size: 0.14rem;
          overflow: scroll;
          border-radius: 0.04rem;
          .classname {
            font-weight: 600;
            margin-left: 0.1rem;
            pointer-events: none;
          }
          .courseName {
            margin-left: 0.1rem;
            pointer-events: none;
          }
          .teacherName {
            margin-left: 0.1rem;
            pointer-events: none;
          }
          .classRoom {
            margin-left: 0.1rem;
            pointer-events: none;
          }
          .errorRow {
            height: 100%;
            border: 0.01rem red dashed;
          }
          .classstyle {
            /*border-left:0.05rem solid;
						border-color: rgba(82,192,255,1);
						background-color: rgba(228,245,255,1);*/
            color: rgb(82, 192, 255);
          }
        }
        .classItem.gray {
          border-left: 0rem solid;
          background-color: rgb(240, 241, 246);
          color: rgb(85, 85, 85);
          background-image: repeating-linear-gradient(
            -45deg,
            rgb(238, 241, 246) 20px,
            rgb(247, 248, 252) 20px,
            rgb(247, 248, 252) 40px,
            rgb(238, 241, 246) 40px,
            rgb(238, 241, 246) 60px
          );
        }
        .classItem.blue {
          border-color: rgb(82, 192, 255);
          background-color: rgb(228, 245, 255);
          color: rgb(82, 192, 255);
        }
        .classItem.yellow {
          border-color: rgb(254, 184, 89);
          background-color: rgb(255, 244, 230);
          color: rgb(254, 184, 89);
        }
        .classItem.red {
          border-color: rgb(254, 130, 140);
          background-color: rgb(255, 229, 232);
          color: rgb(254, 130, 140);
        }
        .classItem.temp {
          border-left: 0.05rem solid;
          border-color: rgb(94, 211, 122);
          background-color: rgb(230, 250, 235);
          color: rgb(30, 173, 64);
        }
        .classItem.thiscls {
          border-left: 0.05rem solid;
          border-color: rgb(82, 192, 255);
          background-color: rgb(228, 245, 255);
          color: rgb(82, 192, 255);
          border-top: 1px solid #52c0ff;
          border-right: 1px solid #52c0ff;
          border-bottom: 1px solid #52c0ff;
        }

        .opacity {
          opacity: 0.3;
        }

        // 滚动条
        .classItem::-webkit-scrollbar {
          width: 0;
          height: 0;
        }
      }
      .clickItem:hover {
        cursor: pointer;
        opacity: 1;
      }
    }
  }
  /**排课选班**/
  .el-dialog-bg {
    background: #ffffff;
    width: 8rem !important;
    border-radius: 0.1rem;
    .el-dialog__header {
      padding: 0px;
    }
    .el-dialog__body {
      padding: 0px !important;
    }
    .el-dialog__footer {
      padding: 0rem 0.3rem 0.3rem 0.3rem;
      .footer-btn {
        width: 100%;
        text-align: center;
      }
    }

    .select-class-panel {
      width: 100%;
      height: auto;
      padding: 0.3rem 0.31rem;
      .title-box {
        width: 100%;
        height: auto;
        font-size: 0.28rem;
        font-weight: bold;
        color: #333333;
        position: relative;
      }
      .select-class-box {
        width: 100%;
        height: auto;
        color: #333333;
        position: relative;
        margin-top: 0.5rem;
        margin-bottom: 0.5rem;
      }
      .select-class-startDate {
        width: 100%;
        height: auto;
        color: #333333;
        position: relative;
        margin-top: 0.5rem;
        margin-bottom: 0.5rem;
      }
      .Btn-box {
        width: 100%;
        height: auto;
        color: #333333;
        position: relative;
        display: inline-flex;
        justify-content: center;
      }
    }
  }
}
</style>